package oa.hleast.xswl.common.config.pay;

import cn.hutool.core.io.IoUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.AntCertificationUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

@Slf4j
@Configuration
@EnableAsync
@AllArgsConstructor
public class AlipayConfig {


    private static final String ALIPAY_APP_ID = "2021000118630363";
    private static final String ALIPAY_APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHvknUrbtjg1LRyp9EKPU3Phs5PDBKlxWbVhvMp0pKm1JZRknWSmCtjKf12AkgC0oq/VYZMUwB9uFxKqJzd1UPNrquW8HU09jFfeIIahoDHPLz+RnuuXMqmjc0ezj5McBWOh8uuQSCiSxm2eS5mflE99oGXIcjycmTeGbG8noaJcWPWeXmGV7sgVx06skaaWsOJwFgzHTyYk27MBPgHcPWOYfmYATAH+lEvRJebwyg66dIRuSWX4R74FdDBu+m9f/s/Pu4x5lggMG9V+dJxecVQRiie7h9U9hcOgspEr58dLa/0oM08f6SqGpDLZd+p2by+aAs3dCENmDqiwpRNyDjAgMBAAECggEAGRF8QwmejJ8pAVNhHE5QEtamYmiKJoxGUjyRv7a5UpPinlgLtMZhmktajV1LOh67oLrOVrKy7b3xHlwYSiikjb22thJ99lb1Nmur/Y/So/aJq6K6NksLSLfYMBn9iI+2jHYJYjCK86xvhcMBqYEU9rarDfeygVp3noNiv6TyBbfj/6EVjXpHYKwTj8XioViwWeE9IxTsIAbdCCj2QWtcNgZc6vNvDUXQjITKj7kZKw9fHatrZJfak7YkRUIU4TprF0tqDF8DJpr1r8/4u9HCNtTgxloZH03mmBSEDBNj0621NopBql/c5JZDVotwC8MUV2jpQhQSwQHM8ZTgLSXiEQKBgQDgNjbhDjUc+ktKE5ekeOPDItCxz5Wl1BLHxgYQBiXfoerJlqboa+A9bvo7hfxJ9vGgTwl8yKmsmDF50vBiiWKUjiixzT42ZD5Fbc+ZYu44405Dt7ouR3/hXtasEErN/8vGoTsbO3o9FUkrR5ptGoqUV1Qq8llyremQsSawh4mI2wKBgQCa/RqIgFOqxoCFaCBOjIL53tLvzm0UhLpRPzd1cxgdB/Cuwhq/SeMdZFEgJY3Am+DPg0Pa/vJKoDb/jBXp7Ekw6bjpPWSM5SjdVrXKTL3KOtn8l8e/nCjpmeNLdJd2Ki2FBdV7doxaHIkxDDnfFiT8LpqCIaKzpe9zUUazeInimQKBgF59GoWf+iw7Iy2VsiuDMuFSs8arp/JZvIxqXLW2EZH8Z7kK/04l4DujoFsjbR4yrsOTa3kmC7OL9BXWGq48HcpjWq0LxPMhLckOrRWERsa8rIgHTrQgN7lfwXKD7zJ/YX5VBlbEqxBA/zP5GhBuxgYcA4GR3rZgqnTq41Yz2HdPAoGADH8DuKXAGTDQA/GVSUAC/2p7z2HxYYoiC5LxQcL52r1dJnn39hxa92+zKshcWX837QNEYU/U8Tdht9Dvo2CttgfiJMwSY1nGpbHsDleJpdiA4uDJ9iT9F3iU3uyTma9k5CjIQaAZSNqsJQw7TkVWzg5j3sIfgCSM3dtbu/SoCWECgYEAk+p+0l/gNwwIZ489emRsscvCJf8joJhDpbYF7glshmn+9E7D5c4xGVANqp0/Na+lRUbg9wO5tEKcTlWc+KW9290YeWPgvHi4/shU09d3urPyDxlfs9orB0fyyyc3SjoldzAg9bxBHySWluy8PYL5mFMIRTwXc4FKnEF8/+/Y29E=";


    @Bean
    public AlipayClient alipayClient() {

        System.out.println("test12111111111111111111111111111111111111");

        String crsPath = "devcsr" + File.separator;
        // 支付宝应用证书 绝对路径
        String alipayCertPath = crsPath + "appCertPublicKey_2021000118630363.crt";
        // 支付宝公钥证书 绝对路径
        String alipayCertPublicKeyPath = crsPath + "alipayCertPublicKey_RSA2.crt";
        // 支付宝根证书 绝对路径
        String alipayRootCertPath = crsPath + "alipayRootCert.crt";

//        String publicKey = null;
//        try {
//            publicKey = AlipaySignature.getAlipayPublicKey(alipayCertPath);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }

//        sn(alipayCertPath, alipayRootCertPath, alipayCertPublicKeyPath);

        String serverUrl = "https://openapi.alipaydev.com/gateway.do";
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //gateway:支付宝网关（固定）https://openapi.alipay.com/gateway.do
        certAlipayRequest.setServerUrl(serverUrl);
        //APPID 即创建应用后生成,详情见创建应用并获取 APPID
        certAlipayRequest.setAppId(ALIPAY_APP_ID);
        //开发者应用私钥，由开发者自己生成
        certAlipayRequest.setPrivateKey(ALIPAY_APP_PRIVATE_KEY);
        //参数返回格式，只支持 json 格式
        certAlipayRequest.setFormat("json");
        //请求和签名使用的字符编码格式，支持 GBK和 UTF-8
        certAlipayRequest.setCharset("UTF-8");
        //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐商家使用 RSA2。
        certAlipayRequest.setSignType("RSA2");
        // todo: 需要把3个证书文件路径换成证书内容
        //应用公钥证书路径（app_cert_path 文件绝对路径）
//        certAlipayRequest.setCertPath(alipayCertPath);
        //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
//        certAlipayRequest.setAlipayPublicCertPath(alipayCertPublicKeyPath);
        //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
//        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        AlipayClient alipayClient = null;
        try {

            Resource certResource = new ClassPathResource(alipayCertPath);
            String certContent = IoUtil.read(certResource.getInputStream(), "utf-8");
            certAlipayRequest.setCertContent(certContent);

            Resource alipayCertResource = new ClassPathResource(alipayCertPublicKeyPath);
            String alipayCertContent = IoUtil.read(alipayCertResource.getInputStream(), "utf-8");
            certAlipayRequest.setAlipayPublicCertContent(alipayCertContent);

            Resource alipayRootResource = new ClassPathResource(alipayRootCertPath);
            String alipayRootContent = IoUtil.read(alipayRootResource.getInputStream(), "utf-8");
            certAlipayRequest.setRootCertContent(alipayRootContent);

            // 请求网关 (gateway)、应用 id (app_id)、应用私钥 (private_key)、编码格式 (charset)、支付宝公钥 (alipay_public_key)、签名类型 (sign_type)
//            alipayClient = new DefaultAlipayClient(serverUrl, ALIPAY_APP_ID, ALIPAY_APP_PRIVATE_KEY, "json", "UTF-8", publicKey, "RSA2");
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return alipayClient;
    }


    private void sn(String alipayCertPath, String alipayRootCertPath, String alipayCertPublicKeyPath) {
        System.out.println("alipayCertPath = " + alipayCertPath);
        System.out.println("alipayRootCertPath = " + alipayRootCertPath);
        System.out.println("alipayCertPublicKeyPath = " + alipayCertPublicKeyPath);

        String app_cert_sn = null;
        try {
            app_cert_sn = AlipaySignature.getCertSN(alipayCertPath);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        File file = new File(alipayRootCertPath);
        String client = null;
        try {
            client = FileUtils.readFileToString(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String alipay_root_cert_sn = AntCertificationUtil.getRootCertSN(client);

        String alipay_cert_public_key_sn = null;
        try {
            alipay_cert_public_key_sn = AlipaySignature.getAlipayPublicKey(alipayCertPublicKeyPath);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        System.out.println("=======================");
        System.out.println("app_cert_sn: " + app_cert_sn);
        System.out.println("alipay_root_cert_sn: " + alipay_root_cert_sn);
        System.out.println("alipay_cert_public_key_sn: " + alipay_cert_public_key_sn);
        System.out.println("=======================");

        String publicKey = null;
        try {
            publicKey = AlipaySignature.getAlipayPublicKey(alipayCertPath);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        System.out.println();
        System.out.println("应用公钥数据：" + publicKey);
        System.out.println();
    }

}
